package edu.whcp.comp2301.controller.viewController;

import edu.whcp.comp2301.dao.UserDao;
import edu.whcp.comp2301.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/page")
public class PageLoginController {
    @Autowired
    private UserDao userDao;

    @GetMapping("/login")
    public String redirectLogin() {
        return "frontend/login";
    }

    @PostMapping(value = "/login",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Integer login(@RequestParam String username, @RequestParam String password, HttpSession session) {
        User user = userDao.userLogin(username, password);
        if(user==null) {
            return 0;
        }
        if(user.getStatus()==0){
            return -1;
        }
        session.setAttribute("user", username);
        session.setAttribute("role", user.getRole());
        session.setAttribute("status",user.getStatus());
        return 1;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/page/login";
    }
}
